<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/26
 * Time: 14:54
 */


namespace App\Api\Admin\Controllers;

use App\Exceptions\ApiException;
use App\Models\AdminMenu;
use App\Services\Admin;
use Illuminate\Http\Request;
use App\Models\Admin\Log;
use App\Models\Admin\Role;

class JurisdictionControllers extends CommonController
{
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * @desc 菜单列表
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $parent_id = $request->input('parent_id');
        if(empty($parent_id)){
            $parent_id = 0;
        }else{
            $parent_id = $parent_id;
        }
      /*  $collection = AdminMenu::select('title as name', 'id', 'parent_id','order','uri')->get()->toArray();
        $list = (new AdminMenu)->getDepartments($collection);*/
        $list = AdminMenu::where('parent_id',$parent_id)->select('id','title','order','parent_id','uri')->orderBy('order','asc')->skip($offset)->take($pagesize)->get();
        foreach ($list as $item){
            $item['url']= $item->uri ?? '';
            $item['subordinate_menu']= AdminMenu::where('parent_id',$item->id)->select('id','title','order','parent_id','uri')->orderBy('order','asc')->get() ;
            foreach ($item['subordinate_menu'] as $v){
                $v['url']= $v->uri ?? '';
                unset($v->uri);
            }
            unset($item->uri);
        }
        $total = AdminMenu::where('parent_id', $parent_id)->count();
        $totalPage = ceil($total / $pagesize);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $list]);
    }

    /**
     * @desc 添加菜单
     * @return array
     */
    public function AddMenu()
    {
        $parent_id = IT('parent_id',true,'请输入栏目id');
        $title = IT('title',true,'请输入栏目名称');
        $order = IT('order',true,'请输入排序');
        $url = IT('url');

        // 判断上一级菜单是否存在
        if($parent_id != 0) {
            $is_record = AdminMenu::where(['id' => $parent_id])->first(['id']);
            if(!$is_record) {
                return json_error('上一级菜单不存在');
            }
        }

        $check= AdminMenu::where(['title' => $title, 'parent_id' => $parent_id])->first(['id']);
        if($check){
            return json_success('栏目名称已存在');
        }
        $insert_date=[
            'parent_id'=>$parent_id,
            'order'=>$order,
            'title'=>$title,
            'uri'=>$url,
            'created_at'=> time2date(),
            'updated_at' => time2date()

        ];
        $insert_rs  = AdminMenu::insert($insert_date);
        if(!$insert_rs){
            return json_error('添加菜单失败');
        }
        (new Log)->add($this->user,'添加了菜单名称为-'.$title);
        return json_success('添加菜单成功');
    }

    /**
     * @desc 修改/删除菜单
     * @return array
     * @throws \Exception
     */
    public function MenuOperation()
    {
        $id =IT('id',true,'请输入栏目id');
        $operation =IT('operation',true,'请填写你要操作行为');
        $check= AdminMenu::where('id',$id)->first();
        if(!$check){
            return json_error('栏目不存在');
        }
        if($operation=='del'){
            $del_rs = $this->_DelMeun($id);
            if($del_rs){
                (new Log)->add($this->user,'删除了栏目'.'名称为-'.$check->title);
                 return json_success('删除成功');
             }else{
                 return json_error('删除失败');
            }
        }
        if($operation=='edit'){
            $title = '';
            $update_rs = $this->_EditMeun($id, $title);
            if($update_rs){
                (new Log)->add($this->user,'修改了栏目'.'名称为-'.$title);
                return json_success('修改成功');
            }else{
                return json_error('修改失败');
            }
        }
    }

    /**
     * @desc 编辑菜单
     * @param $id
     * @param $title
     * @return mixed
     * @throws \Exception
     */
    public function _EditMeun($id, &$title)
    {
        $parent_id= IT('parent_id', true, '请选择上级菜单');
        $order = IT('order', true, '请选择排序');
        $title = IT('title', true, '请输入菜单名称');
        $url =  IT('url');
        // 判断上一级菜单是否存在
        $is_record= AdminMenu::where(['id' => $parent_id])->first(['id']);
        if(!$is_record) {
            EE('上一级菜单不存在');
        }
        // 检测同一级下菜单是否有重复
        $is_record = AdminMenu::select(['id'])->where(['parent_id' => $parent_id, 'title' => $title])->first();
        if($is_record && ($is_record->id != $id)) {
            EE('该菜单名已经存在');
        }

        $menu_data = [
            'parent_id' => $parent_id,
            'title' => $title,
            'order' => $order,
            'uri' => $url,
            'updated_at' => time2date(),
        ];

        return AdminMenu::where('id',$id)->update($menu_data);
    }

    /**
     * @desc 删除菜单
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function _DelMeun($id)
    {
        // 删除菜单时，检测菜单是否有下级
        $son_list = AdminMenu::where(['parent_id' => $id])->first(['id']);
        if($son_list) {
            EE('请先把下级菜单移除，在删除该菜单');
        }

        // 删除角色对应权限
        $role_list = Role::where([])->get(['id', 'permissions']);
        if($role_list) {
            foreach($role_list as $role) {
                if(empty($role['permissions']) || ($role['permissions'] == '*')) {
                    continue;
                }

                $permissions_list = explode(',', $role->permissions);
                if(in_array($id, $permissions_list)) {
                    unset($permissions_list[array_search($id, $permissions_list)]);
                    $permissions_list = $permissions_list ? implode(',', $permissions_list) : '';
                    Role::where('id', $role['id'])->update(['permissions' => $permissions_list]);
                }
            }
        }

        return AdminMenu::where('id',$id)->delete();
    }

    /**
     * @desc 菜单详情
     * @return array
     */
    public function MeunDetails(){
        $url= IT('url',true,'请填写URL');
        $details= AdminMenu::where('uri',$url)->select('id','title','order','parent_id','uri')->first();
        if(!$details){
            return json_error('该栏目不存在');
        }
     /* $father_name = AdminMenu::where('id',$details->parent_id)->value('title');*/
        $sub_level = AdminMenu::where('parent_id',$details->id)->get(['id','title','uri']);
      /* $details->father_name= $father_name ?? '' ;
        $details->url= $details->uri;
        unset($details->uri);*/
        foreach ($sub_level as $k){
             $k->url = $k->uri;
             unset($k->uri);
        }
        return json_success('ok',$sub_level);
    }
    /**
     * @desc 菜单权限列表
     * @return array
     */
    public function MenuPermissionsList()
    {
        $menu_list = AdminMenu::where('parent_id',0)->select('id','title')->orderBy('order','ASC')->get();
        foreach ($menu_list as &$item){
            $item->subordinate_menu = AdminMenu::where('parent_id',$item->id)->select('id','title')->orderBy('order','asc')->get();
            foreach ($item->subordinate_menu as &$v){
                $v->subordinate_menu = AdminMenu::where('parent_id',$v->id)->select('id','title')->orderBy('order','asc')->get();
            }
        }

        return json_success('ok',$menu_list);
    }
}